package club.cearnach.api.service.impl;

import club.cearnach.api.dao.IActorDao;
import club.cearnach.entity.Actor;
import club.cearnach.entity.Person;
import club.cearnach.api.form.PageBean;
import club.cearnach.api.service.IActorService;
import club.cearnach.api.service.IPersonService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;

/**
 * @author 阮胜
 * @date 2018/5/12 17:03
 */
@Service
public class ActorServiceImpl implements IActorService {
    private final IActorDao actorDao;
    @Autowired
    private IPersonService personService;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")


    public ActorServiceImpl(IActorDao actorDao) {
        this.actorDao = actorDao;
    }

    @Override
    public Actor save(Actor actor) {
        linkPerson(actor);
        return actorDao.saveAndFlush(actor);
    }

    @Override
    public Actor saveAndFlush(Actor actor) {
        linkPerson(actor);
        return actorDao.saveAndFlush(actor);
    }

    /**
     * 与person建立联系
     *
     * @param actor
     */
    private void linkPerson(Actor actor) {
        Optional<Actor> ac = actorDao.findByName(actor.getName());
        ac.ifPresent(actor1 -> BeanUtils.copyProperties(actor1, actor));
        Person person = personService.findByNameOne(actor.getName());
        actor.setPerson(person);
    }

    @Override
    public Optional<Actor> findByName(String name) {
        return actorDao.findByName(name);
    }

    @Override
    public HashSet<Actor> saveMany(String actors) {
        HashSet<Actor> actorSet = new HashSet<>();
        if (!StringUtils.isEmpty(actors)) {
            String[] actorArr = actors.split("/");
            for (String actor : actorArr) {
                Actor ac = saveAndFlush(new Actor(actor));
                actorSet.add(ac);
            }
        }
        return actorSet;
    }

    @Override
    public Optional<Actor> findByPersonId(Integer id) {
        return actorDao.findByPersonId(id);
    }

    @Override
    public void delete(Integer id) {
        actorDao.deleteById(id);
    }

    @Override
    public Optional<Actor> findById(Integer id) {
        return actorDao.findById(id);
    }

    @Override
    public List<Actor> findAllByOrderByUpdateDateDesc(PageBean pageBean) {
        return actorDao.findAllByOrderByUpdateDateDesc(PageRequest.of(pageBean.getPage(),pageBean.getSize()));
    }
}
